package com.zis.platform.core.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zis.Constants;
import com.zis.platform.common.util.CacheCoreUtil;
import com.zis.platform.core.entity.base.ResBase;

/**
 * 资源
 * 
 * @author zhaohaitao
 * 
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResEntity extends ResBase implements Serializable, Comparable<ResEntity>
{
    
    /**
     * 
     */
    private static final long serialVersionUID = -7512156959804880621L;
    
    /** default constructor */
    public ResEntity()
    {
    }
    
    /**
     * 返回字典名称
     * 
     * @return
     */
    public String getResTypeName()
    {
        if (StringUtils.isNotEmpty(getResType()))
        {
            DictionaryEntity dictionary = CacheCoreUtil.getDictionaryByValue(getResType());
            if (dictionary != null)
            {
                return dictionary.getDictName();
            }
        }
        return null;
    }
    
    public String getEnabledName()
    {
        if (getIsEnabled())
        {
            return "是";
        }
        return "否";
    }
    
    /**
     * 遍历获取当前资源下的菜单
     * 
     * @return
     */
    public List<ResEntity> getChildrenMenus()
    {
        List<ResEntity> menus = new ArrayList<ResEntity>();
        if (!CollectionUtils.isEmpty(children))
        {
            for (ResEntity res : children)
            {
                if (res.getIsEnabled() && Constants.RES_TYPE_MENU.equals(res.getResType()))
                {
                    menus.add(res);
                }
            }
        }
        Collections.sort(menus);
        return menus;
    }
    
    /**
     * 判断当前资源是否为菜单
     * 
     * @return
     */
    @JsonIgnore
    public boolean isMenu()
    {
        return Constants.RES_TYPE_MENU.equals(getResType());
    }
    
    public void addChildRes(ResEntity res)
    {
        List<ResEntity> list = getChildren();
        if (CollectionUtils.isEmpty(list))
        {
            list = new ArrayList<ResEntity>();
        }
        list.add(res);
        Collections.sort(list);
        setChildren(list);
    }
    
    @Override
    public int compareTo(ResEntity o)
    {
        if (o.getOrderNum() > this.getOrderNum())
        {
            return -1;
        }
        else
        {
            return 1;
        }
    }
    
    @Override
    public boolean equals(Object obj)
    {
        return super.getResId().equals(obj);
    }
    
    @Override
    public String toString()
    {
        return super.getResId().toString();
    }
    
}
